import { Application, FrontendSession } from 'pinus';
import { logger } from "../../../util/Logger";

export default function (app: Application) {
    return new Handler(app);
}

export class Handler {
    constructor(private app: Application) {

    }

    /**
     * 当有新的客户端连接上来时，把客户端 session 绑定以及将客户端加入到 channel 中
     *
     * @param  {Object}   msg     request message
     * @param  {Object}   session current session object
     */
    async entry(msg: { rid: string, username: string }, session: FrontendSession) {

        //处理uid和rid
        let self = this;
        let rid = msg.rid;
        let uid = msg.username + "*" + rid;
        if(!rid || !uid){
            return {
                code:500,
                msg:"用户名字和房间号码不能为空"
            }
        }

        //检测是否重复登录
        let sessionService = self.app.get("sessionService");
        if (!!sessionService.getByUid(uid)) {
            return {
                code: 500,
                msg: "不能重复登录"
            }
        }

        //绑定session
        await session.abind(uid);
        session.set("rid", rid);
        session.push("rid", function (err) {
            if (err) {
                logger.error("为session设置rid失败", err.stack)
            }
        })

        //当客户端断开连接时
        session.on("close", this.onUserLeave.bind(this));

        //把当前客户端加入channel
        let users = await self.app.rpc.chat.chatRemoter.add.route(session)(uid, self.app.getServerId(), rid, true);
        console.log("所有用户名字：",users);

        return { code: 200, msg: 'game server is ok.',data:{
            users:users
        } };
    }

    /** 当用户断开连接时 */
    onUserLeave(session: FrontendSession) {
        if (!session || !session.uid) {
            return;
        }

        //跟后端服务器讲，将客户端从 channel 中移除（涉及rpc调用）
        this.app.rpc.chat.chatRemoter.kick.route(session)(session.uid,this.app.get("serverId"),session.get("rid"));
    }

}